<template>
  <div class="tinymce-container">
    <h2>TinyMCE 编辑器</h2>
    <div class="editor-wrapper">
      <Editor
        v-model="content"
        :init="editorConfig"
        :api-key="apiKey"
        class="editor"
      />
    </div>

    <div class="content-preview" v-if="showPreview">
      <h3>内容预览</h3>
      <div v-html="content" class="preview-content"></div>
    </div>
    
    <div class="actions">
      <el-button type="primary" @click="togglePreview">{{ showPreview ? '隐藏预览' : '显示预览' }}</el-button>
      <el-button type="success" @click="saveContent">保存内容</el-button>
      <el-button @click="clearContent">清空内容</el-button>
      <el-button type="info" @click="loadSavedContent">加载保存的内容</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Editor from '@tinymce/tinymce-vue'

// TinyMCE 插件列表
const plugins = [
  'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
  'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
  'insertdatetime', 'media', 'table', 'help', 'wordcount',
  'paste'
]

const apiKey = import.meta.env.VITE_TINYMCE_API_KEY || 'no-api-key'
const content = ref('')
const showPreview = ref(false)
const STORAGE_KEY = 'tinymce_editor_content'

const editorConfig = {
  language: 'zh_CN',
  height: 500,
  resize: true,
  branding: false,
  base_url: '/tinymce',
  skin_url: '/tinymce/skins/ui/oxide',
  content_css: '/tinymce/skins/content/default/content.css',
  menubar: 'file edit view insert format tools table',
  plugins,
  toolbar: 'undo redo | formatselect | ' +
    'bold italic backcolor forecolor | alignleft aligncenter ' +
    'alignright alignjustify | bullist numlist outdent indent | ' +
    'removeformat | code | paste | help',
  content_style: `
    body {
      font-family: -apple-system, BlinkMacSystemFont, San Francisco, Segoe UI, Roboto, Helvetica Neue, sans-serif;
      font-size: 14px;
      line-height: 1.6;
      padding: 20px;
      margin: 0;
      min-height: 100vh;
    }
    p { margin: 0 0 1em; }
  `,
  paste_data_images: true,
  paste_as_text: false,
  paste_enable_default_filters: true,
  paste_word_valid_elements: "b,strong,i,em,h1,h2,h3,h4,h5,h6,p,ol,ul,li,a[href],br,table,tbody,thead,tr,td,th",
  paste_webkit_styles: "color font-size font-family background-color",
  paste_retain_style_properties: "all",
  browser_spellcheck: true,
  contextmenu: false,
  setup: function(editor) {
    editor.on('init', function() {
      editor.getContainer().style.transition = "border-color 0.15s ease-in-out";
    });
    editor.on('focus', function() {
      editor.getContainer().style.borderColor = '#409EFF';
    });
    editor.on('blur', function() {
      editor.getContainer().style.borderColor = '#DCDFE6';
    });
  }
}

// 动态导入 TinyMCE
onMounted(async () => {
  try {
    await import('tinymce/tinymce')
    // 导入主题
    await import('tinymce/themes/silver/theme')
    // 导入图标
    await import('tinymce/icons/default/icons')
    // 动态导入插件
    await Promise.all(plugins.map(plugin => import(/* @vite-ignore */ `tinymce/plugins/${plugin}/plugin`)))
  } catch (error) {
    console.error('Error loading TinyMCE:', error)
    ElMessage.error('编辑器加载失败')
  }
})

// 切换预览
const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 保存内容到本地存储
const saveContent = () => {
  localStorage.setItem(STORAGE_KEY, content.value)
  ElMessage.success('内容已保存')
}

// 加载保存的内容
const loadSavedContent = () => {
  const savedContent = localStorage.getItem(STORAGE_KEY)
  if (savedContent) {
    content.value = savedContent
    ElMessage.success('已加载保存的内容')
  } else {
    ElMessage.warning('没有找到保存的内容')
  }
}

// 清空编辑器内容
const clearContent = () => {
  ElMessageBox.confirm('确定要清空编辑器内容吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    content.value = ''
    ElMessage.success('内容已清空')
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style>
/* 这些样式不能加 scoped，否则会影响不到编辑器 */
.tox.tox-tinymce {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  transition: border-color 0.2s;
}

.tox.tox-tinymce:hover {
  border-color: #C0C4CC;
}

.tox .tox-toolbar__primary {
  background: #F5F7FA !important;
  border-bottom: 1px solid #EBEEF5;
}

.tox .tox-edit-area__iframe {
  background: #FFFFFF;
}

.tox .tox-statusbar {
  border-top: 1px solid #EBEEF5 !important;
}

/* 编辑器内容区域样式 */
.tox-tinymce {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
</style>

<style scoped>
.tinymce-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.tinymce-container h2 {
  margin-bottom: 20px;
  color: #303133;
}

.editor-wrapper {
  margin: 20px 0;
}

.content-preview {
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background: #FFFFFF;
}

.content-preview h3 {
  margin-bottom: 15px;
  color: #303133;
}

.preview-content {
  min-height: 100px;
  padding: 10px;
}

.actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .tinymce-container {
    padding: 10px;
  }
  
  .actions {
    flex-wrap: wrap;
  }
  
  .actions .el-button {
    flex: 1;
    min-width: 120px;
  }
}
</style>